package pipe.characterstream;

import java.io.*;

class Sender implements Runnable {

    private PipedWriter out = new PipedWriter();
    private File srcFile;

    public Sender(File srcFile) {
        this.srcFile = srcFile;
    }

    public PipedWriter getOutputStream() {
        return out;
    }

    public void run() {
        BufferedReader bin = null;
        char[] b = new char[1024];
        try {
            bin = new BufferedReader(new FileReader(this.srcFile));
            int len = -1;
            while ((len = bin.read(b)) != -1) {
                out.write(b, 0, len);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bin != null) {
                    bin.close();
                    bin = null;
                }
                if (out != null) {
                    out.close();
                    out = null;
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
}

class Receiver implements Runnable {
    private PipedReader in = new PipedReader();
    private File destFile;

    public Receiver(File destFile) {
        this.destFile = destFile;
    }

    public PipedReader getInputStream() {
        return in;
    }

    public void run() {
        BufferedWriter bout = null;
        char[] b = new char[1024];
        try {
            bout = new BufferedWriter(new FileWriter(destFile));
            int len = -1;
            while ((len = in.read(b)) != -1) {
                bout.write(b, 0, len);
            }
            bout.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bout != null) {
                    bout.close();
                    bout = null;
                }
                if (in != null) {
                    in.close();
                    in = null;
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
}

public class PipedWriterDemo {

    public static void main(String[] args) {
        File srcFile = new File("d:" + File.separator + "MyUtils.java");
        File destFile = new File("e:" + File.separator + "MyUtils.java");
        try {
            Sender sender = new Sender(srcFile);    // 创建线程对象Sender
            Receiver receiver = new Receiver(destFile);    // 创建线程对象Receiver
            PipedWriter out = sender.getOutputStream();    // 写入
            PipedReader in = receiver.getInputStream();    // 读出
            out.connect(in); // 将输出发送到输入
            Thread senderThread = new Thread(sender);
            Thread receiverThread = new Thread(receiver);
            senderThread.start();// 启动线程
            receiverThread.start();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
